package cn.cf.kxx.tools;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

public class UpgradeManager {

    private Context mContext;
    private DownloadManager mDownloadManager; // 声明一个下载管理器对象
    private long mDownloadId = 0; // 下载编号


    public UpgradeManager(Context context) {
        mContext = context;
        mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        startDownload("http://116.204.121.65:27/down/app-release.apk");

        // 注册接收器，注册之后才能正常接收广播
        context.registerReceiver(completeReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private void shutdown(){
        if(completeReceiver != null){
            mContext.unregisterReceiver(completeReceiver);
        }
    }

    private void startDownload(String url) {
        Uri uri = Uri.parse(url); // 根据下载地址构建一个Uri对象
        DownloadManager.Request down = new DownloadManager.Request(uri); // 创建一个下载请求对象，指定从哪里下载文件
        down.setTitle("下载信息"); // 设置任务标题
        down.setDescription("安装包正在下载"); // 设置任务描述
        // 设置允许下载的网络类型
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        // 设置通知栏在下载进行时与完成后都可见
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        // 设置下载文件在私有目录的保存路径。从Android10开始，只有保存到公共目录的才会在系统下载页面显示，保存到私有目录的不在系统下载页面显示
        down.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, "kxx.apk");
        // 设置下载文件在公共目录的保存路径。保存到公共目录需要申请存储卡的读写权限
        //down.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, pos + ".apk");
        mDownloadId = mDownloadManager.enqueue(down); // 把下载请求对象加入到下载队列
    }

    private DownloadCompleteReceiver completeReceiver = new DownloadCompleteReceiver(); // 创建一个下载完成的广播接收器

    // 定义一个下载完成的广播接收器。用于接收下载完成事件
    private class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent1) {
            if (intent1.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) { // 下载完毕
                // 从意图中解包获得下载编号
                long downId = intent1.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                Log.d("dong", "下载完成 id : " + downId + ", mDownloadId=" + mDownloadId);
                //                // 下载完成，获取下载文件路径
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(mDownloadId);
                Cursor cursor = mDownloadManager.query(query);
                if (cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(columnIndex)) {
                        @SuppressLint("Range") String downloadFileUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        Log.e("dong",downloadFileUri);


//                            Intent installIntent = new Intent(Intent.ACTION_VIEW);
//                            Uri fileUri = FileProvider.getUriForFile(mContext, "cn.cf.kxx", new File(downloadFileUri));
//                            installIntent.setDataAndType(fileUri, "application/vnd.android.package-archive");
//                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            mContext.startActivity(installIntent);

//                            Intent intent = new Intent(Intent.ACTION_VIEW);
//                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                            String authority = "com.example.fileprovider";
//                            Uri fileUri = FileProvider.getUriForFile(mContext, authority, new File(apkUri));
//                            intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
//                            mContext.startActivity(intent);
                        File file = new File(Uri.parse(downloadFileUri).getPath());

                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//安装完成后打开新版本
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 给目标应用一个临时授权
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                            //如果SDK版本>24，即：Build.VERSION.SDK_INT > 24，使用FileProvider兼容安装apk

                            Uri uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file);
                            intent.setDataAndType(uri, "application/vnd.android.package-archive");
                        } else {
                            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                        }
                        mContext.startActivity(intent);
                    }
                }
            }
        }
    }









//    private Context mContext;
//    private DownloadManager mDownloadManager;
//    private long mDownloadId = -1;
//

//
//    public void checkVersionAndUpdate() {
//        // 调用后台接口获取版本信息，判断是否需要升级
//
//        // 如果需要升级，获取新版本的下载链接
//        String downloadUrl = "http://116.204.121.65:27/down/app-release.apk"; // 替换为实际的下载链接
//
//        // 开始下载
//        startDownload(downloadUrl);
//    }
//
//    @SuppressLint("UnspecifiedRegisterReceiverFlag")
//    private void startDownload(String downloadUrl) {
//        Uri uri = Uri.parse(downloadUrl);
//
//        DownloadManager.Request request = new DownloadManager.Request(uri);
//        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "app.apk");
//        request.setTitle("App Upgrade");
//        request.setDescription("Downloading...");
//
//        mDownloadId = mDownloadManager.enqueue(request);
//
//        Log.e("dong",mDownloadId + " id");
////         注册下载完成广播接收器
//        mContext.registerReceiver(mDownloadCompleteReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
//
//        timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                queryDownloadProgress(mContext,mDownloadId);
//            }
//        },1000,2000);
//
//    }
//
//    Timer timer;
//
//    @SuppressLint("Range")
//    private void queryDownloadProgress(Context context, long downloadId) {
//        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
//        DownloadManager.Query query = new DownloadManager.Query();
//        query.setFilterById(downloadId);
//        Cursor cursor = downloadManager.query(query);
//        if (cursor.moveToFirst()) {
//            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
//            int downloadedBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
//            int totalBytes = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
//
//            // 计算下载进度
//            int progress = (int) ((downloadedBytes * 100L) / totalBytes);
//            Log.e("dong","progress:"+progress);
//            if(timer != null && progress == 100){
//                timer.cancel();
//            }
//            // 处理下载进度逻辑
//        }
//        cursor.close();
//    }
//
//    private BroadcastReceiver mDownloadCompleteReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            long completedDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//            if (completedDownloadId == mDownloadId) {
//                // 下载完成，获取下载文件路径
//                DownloadManager.Query query = new DownloadManager.Query();
//                query.setFilterById(mDownloadId);
//                Cursor cursor = mDownloadManager.query(query);
//                if (cursor.moveToFirst()) {
//                    int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
//                    if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(columnIndex)) {
//                        @SuppressLint("Range")
//                        String downloadFileUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
//                        // 安装应用
//                        try {
//                            installApp(downloadFileUri);
//                        }catch (Exception e){
//                            e.printStackTrace();
//                        }
//                    }
//                }
//                cursor.close();
//
//                // 注销广播接收器
//                mContext.unregisterReceiver(mDownloadCompleteReceiver);
//            }
//        }
//    };
//
//    private void installApp(String apkUri) {
////        Intent intent = new Intent(Intent.ACTION_SEND);
////        intent.setType("application/vnd.android.package-archive");
////        intent.putExtra(Intent.EXTRA_STREAM, apkUri);
////        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
////        mContext.startActivity(intent);
//
//
////        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
////        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
////        mContext.startActivity(intent);
//
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        String authority = "com.example.fileprovider";
//        Uri fileUri = FileProvider.getUriForFile(mContext, authority, new File(apkUri));
//        intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
//        mContext.startActivity(intent);
//    }
}
